package com.example.demo.utils;

import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;

public class ComputeSignatureUtil {
    public static final String NONCE = "nonce";
    public static final String TIMESTAMP = "timestamp";
    public static final String SIGNATURE = "signature";
    public static final String APP_CODE = "appcode";

    private ComputeSignatureUtil() {
    }

    public static String computeSignature(String appcode,String nonce,Long timestamp,String body,String appsecret)throws Exception{
        StringBuffer str = new StringBuffer();
        str.append(appcode);
        str.append( new String(Base64.getEncoder().encode(DigestUtils.sha256(body.getBytes(StandardCharsets.UTF_8)))));
        str.append(timestamp);
        str.append(nonce);
        String data = str.toString();
        SecretKeySpec e = new SecretKeySpec(appsecret.getBytes("UTF8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(e);
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF8"));
        String signature = new String(Base64.getEncoder().encode(rawHmac));
        signature = signature.replace(" ", "+");
        return URLEncoder.encode(signature, "utf-8");
    }
     public static  String getNonce(){
         String val = "";
         Random random = new Random();
         //length为几位密码
         for(int i = 0; i < 6; i++) {
             String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
             //输出字母还是数字
             if( "char".equalsIgnoreCase(charOrNum) ) {
                 //输出是大写字母还是小写字母
                 int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                 val += (char)(random.nextInt(26) + temp);
             } else if( "num".equalsIgnoreCase(charOrNum) ) {
                 val += String.valueOf(random.nextInt(10));
             }
         }
         return val;
     }
    public static  Long gettimestamp(){
        Long timestamp = System.currentTimeMillis();
        return timestamp/1000;
    }

    public static void main(String[] args) throws Exception{
        String appsecret = "8ma4m6XCKqmuSwInPxM5fg==";
        Long timestamp = 1594022021L;
        String nonce =  "2e76d3";
        String appcode= "40401";
        String signature = ComputeSignatureUtil.computeSignature(appcode,nonce,timestamp,"",appsecret);
        System.out.println(signature);
    }

}

